<script setup>
import { findAll } from '@/api/index';
import { onMounted, unref, ref } from 'vue';

let domList = []
const wrapper = ref(null)

const getData = () => {
  findAll().then(res => {
    if(res.code == '0') {
      console.log(res.data)
    }
  })
}

const getImgs = (el) => {
  domList.push(el)
}

const scrollListener = () => {
  // let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  let scrollTop = unref(wrapper).scrollTop
  // let winHeight= window.innerHeight;
  let winHeight = 400
  for(let i = 5; i < 10; i++){
    let elem = unref(domList[i])
    if(elem.offsetTop < scrollTop + winHeight){
      let imgSrc = elem.getAttribute('val');
      if (imgSrc) {
        setTimeout(() => {
          elem.src = imgSrc
          elem.removeAttribute('val');
        }, 1500)
      }
    }
  }
}

const initData = () => {
  for(let i = 0; i < 5; i++){
    let elem = unref(domList[i])
    let imgSrc = elem.getAttribute('val');
    if (imgSrc) {
      setTimeout(() => {
        elem.src = imgSrc
        elem.removeAttribute('val');
      }, 1500)
    }
  }
}

onMounted(() => {
  // getData()
  initData()
})
</script>

<template>
<div class="wrapper" @scroll="scrollListener" ref="wrapper">
  <img v-for="item in 10" :ref="getImgs" src="../../../src/images/loading.gif" :val="'../../../src/images/'+(item+1)+'.png'" class="img-item" />
</div>
</template>

<style lang="scss" scoped>
.wrapper {
  width: 400px;
  height: 400px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  overflow: scroll;
  position: relative;
  .img-item {
    width: 100px;
    height: 100%;
  }
}
</style>